package models

import (
	"context"
	"fmt"
	"log"

	"cas_central_server/conf"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var client *mongo.Client = nil
var db *mongo.Database = nil

func initDB() error {
	// Set client options
	clientOptions := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s/%s", conf.Config.DBUser, conf.Config.DBPassword, conf.Config.DBHostPort, conf.Config.DBName))

	var err error
	// Connect to MongoDB
	client, err = mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		return err
	}

	// Check the connection
	err = client.Ping(context.Background(), nil)
	if err != nil {
		return err
	}

	db = client.Database(conf.Config.DBName)
	log.Println("connected to MongoDB")
	return nil
}

func closeDB() {
	client.Disconnect(context.Background())
	db = nil
	client = nil
}

func init() {
	if err := initDB(); err != nil {
		panic(fmt.Sprintf("无法连接MongoDB数据库，错误：%v", err))
	}
}
